package com.hmdp.utils.lock;

import cn.hutool.core.lang.UUID;
import com.hmdp.utils.lock.ILock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author 计算机系 ITAEM 摆渡人
 * @description
 * @date 2022/11/7 17:04
 */
@Slf4j
public class SimpleRedisLock implements ILock {

    private String name;
    private StringRedisTemplate stringRedisTemplate;

    //加载lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("lua/unlock.lua"));//载入路径
        UNLOCK_SCRIPT.setResultType(Long.class);//设置返回值
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //锁的同一前缀
    private static final String KEY_PREFIX = "lock:";
    //线程标识，防止集群下多JVW情况下导致线程id重复
    private static final String THREAD_ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = THREAD_ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /*
        解锁前判断这个锁是否属于当前线程的
     */
    @Override
    public void unlock() {
        //调用lua脚本
        stringRedisTemplate.execute(
                //脚本
                UNLOCK_SCRIPT,
                //KEYS
                Collections.singletonList(KEY_PREFIX + name),
                //ARGV
                THREAD_ID_PREFIX + Thread.currentThread().getId()
                );
    }

//    @Override
//    public void unlock() {
//        //获取线程标识
//        String threadId = THREAD_ID_PREFIX + Thread.currentThread().getId();
//        //获取锁中的标识
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        if(threadId.equals(id)){
//            //释放锁
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
//    }
}